#include "BarGenerator.h"
#include "RedisWrapper.h"
#include "LogManager.h"
#include <QDateTime>
#include <nlohmann/json.hpp>
#include <sw/redis++/redis++.h>
#include <fmt/format.h>
#include <QDebug>

namespace Market {

void PeriodGenerator::onTick(const WTSTickStruct& tick) {
    // 将tick.action_time转换为4位时间格式
    QString currentTimeStr = QString::asprintf("%04u", static_cast<unsigned int>(tick.action_time / 100000));   
    // 检查是否需要生成新的Bar
    bool needNewBar = false;
    
    if (!m_hasBar) {
        // 如果是第一个tick，检查当前时间是否在时间点列表中
        needNewBar = m_timePoints.contains(currentTimeStr);
        MLOG_DEBUG("market", "First tick check - Current time: {}, Need new bar: {}", 
            currentTimeStr.toStdString(), needNewBar);
    } else {
        // 获取当前bar的时间点
        QString barTimeStr = QString::asprintf("%04u", static_cast<unsigned int>(m_currentBar.time / 100000));
        
        // 检查是否到达了新的时间点
        if (currentTimeStr != barTimeStr && m_timePoints.contains(currentTimeStr)) {
            // 回调发送当前Bar
            if (m_callback) {
                MLOG_DEBUG("market", "Sending bar callback for time: {}", barTimeStr.toStdString());
                m_callback(m_symbol.toStdString(), m_currentBar);
            }
            needNewBar = true;
        }
    }

    // 生成新的Bar
    if (needNewBar) {
        m_currentBar = WTSBarStruct();

        m_currentBar.time = tick.action_time;
        m_currentBar.date = tick.action_date;
        m_currentBar.open = tick.price;
        m_currentBar.high = tick.price;
        m_currentBar.low = tick.price;
        m_currentBar.close = tick.price;
        m_currentBar.vol = tick.volume;
        m_currentBar.money = tick.turn_over;
        m_currentBar.hold = tick.open_interest;
        m_hasBar = true;
        
    } else if (m_hasBar) {
        // 更新当前Bar
        m_currentBar.high = std::max(m_currentBar.high, tick.price);
        m_currentBar.low = std::min(m_currentBar.low, tick.price);
        m_currentBar.close = tick.price;
        m_currentBar.vol = tick.volume;
        m_currentBar.money = tick.turn_over;
        m_currentBar.hold = tick.open_interest;

    }
}

void BarGenerator::addGenerator(const QString& symbol, TrPeriod period, 
                              const QString& sessionName, BarCallback callback) 
{
    if (m_Generators.contains(symbol))  return;
    
    auto generator = std::make_shared<PeriodGenerator>(symbol, period, sessionName);
    generator->setCallback(callback);
    m_Generators[symbol] = generator;
}


void BarGenerator::onTick(const WTSTickStruct& tick) {
    // 遍历该合约的所有周期生成器
    QString symbol = QString::fromStdString(tick.code);
    if (m_Generators.contains(symbol)) {
        m_Generators[symbol]->onTick(tick);
    }
}

} // namespace Market